/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.dao.AccountDAO;
import model.dao.RoleDAO;
import model.dao.services.AccountDAOServices;
import model.dao.services.RoleDAOServices;
import model.enetities.Account;
import model.enetities.Role;

/**
 *
 * @author Ku81
 */
public class AccountServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        getAccountList(request, response);
        String action = request.getParameter("action");
        System.out.println("actionnnnnnnnnnnnnnn:  "+action);
        if(!action.isEmpty()){
            switch(action){
                case "Delete":
                    deleteAccount(request, response);
                    break;
            }
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

//        String userName = request.getParameter("username");
//        String pwd = request.getParameter("password");
//        String action11 = request.getParameter("submit");
//        System.out.println(userName + " " + pwd + " " + action11);

        String action = request.getParameter("btnSubmit");
        if(!action.isEmpty()){
            switch(action){
                case "Create":
                    insertAccount(request, response);
                    break;
                case "Update":
                    updateAccount(request, response);
                    break;
                case "Delete":
                    deleteAccount(request, response);
                    break;
            }
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void getAccountList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        AccountDAOServices accDAOServices = new AccountDAO();
        List<Account> accountList = accDAOServices.getAccounts();
        request.setAttribute("accountList", accountList);
        request.getRequestDispatcher("accountList.jsp").forward(request, response);
    }

    //INSERT
    public void insertAccount(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html;charset=UTF-8");
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
       
        Account acc = new Account();
        acc.setUserName(request.getParameter("username"));
        acc.setPassword(request.getParameter("password"));
        Role r = new Role(2);
        acc.setIdRole(r);
        acc.setActived(true);
        AccountDAOServices acDAO = new AccountDAO();
        boolean isOK = acDAO.createAccount(acc);
        if(isOK){
            String message = "Insert Successfull.";
            request.setAttribute("message", message);
            request.getRequestDispatcher("accountDetails.jsp").forward(request, response);
//            response.sendRedirect("accountDetails.jsp");
        }else{
            response.getWriter().println("INSERT FAILED.");
        }
    }
    
    //UPDATE
    public void updateAccount(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, 
            IOException{
        response.setContentType("text/html;charset=UTF-8");
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
        
        String accountId = request.getParameter("accountId");
        if (!accountId.isEmpty()) {
            int id = Integer.valueOf(accountId);
            String userName = request.getParameter("username");
            String pass = request.getParameter("password");
            RoleDAOServices roleDAO = new RoleDAO();
            Role role = roleDAO.getRoleByID(2);
            Account acc = new Account(id, userName, pass, role, true);
            AccountDAOServices accDAO = new AccountDAO();
            if (accDAO.updateAccount(acc)) {
                response.sendRedirect("AccountServlet?action=getAccountList");
            } else {
                response.getWriter().print("FAILED");
            }
        }else{
            response.getWriter().print("accountId is null.");
        }        
    }
    
    //DELETE
    public void deleteAccount(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
        String accountId = request.getParameter("accountId");
        if (!accountId.isEmpty()) {
            int id = Integer.valueOf(accountId);
            System.out.println("IDDDDD:  "+id);
            AccountDAOServices accDAO = new AccountDAO();
            Account acc = accDAO.getAccountByID(id);
            if(accDAO.deleteAccount(acc.getIdAccount())){
                getAccountList(request, response);
            }else{
                response.getWriter().print("Cannot delete.");
            }
        }else{
            response.getWriter().print("accountId is null.");
        }
    }
}
